﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using qlqa.Models.LinQ;

namespace qlqa.Delegate.AccountDelegate
{
    public class AccountDelegate
    {
        DatabaseDataContext _database = new DatabaseDataContext();
        UserDelegate.UserDelegate _userDelegate = new UserDelegate.UserDelegate();

        public string[] Login(string username, string password)
        {
            var result = new string[2];
            try
            {
                var res =
                    _database.tb_Users.FirstOrDefault(p => p.Username.Equals(username) && p.Password.Equals(GetMd5Hash(password)) && (p.IsDelete == null || p.IsDelete == false) && p.IsSuDung == true);
                if (res != null)
                {
                    result[0] = "1";
                    result[1] = "";
                    return result;
                }
                result[0] = "0";
                result[1] = "Thất bại!";
                return result;
            }
            catch (Exception ex)
            {
                result[0] = "-1";
                result[1] = ex.Message;
                return result;
            }
        }

        public tb_User GetUser(string username, string password)
        {
            try
            {
                return _database.tb_Users.FirstOrDefault(p => p.Username.Equals(username) && p.Password.Equals(GetMd5Hash(password)) && (p.IsDelete == null || p.IsDelete == false) && p.IsSuDung == true);
            }
            catch (Exception)
            {
                return null;
            }
        }

        public static string GetMd5Hash(string value)
        {
            MD5 md5Hasher = MD5.Create();
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(value));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }

    }
}